package com.ly.system.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ly.common.core.bean.R;
import com.ly.common.core.bean.vo.DictVO;
import com.ly.common.core.utils.excel.ExcelResult;
import com.ly.common.core.utils.excel.ExcelUtil;
import com.ly.system.service.ISysDictService;
import com.ly.system.system.bean.entity.SysDict;
import com.ly.system.system.bean.model.SysDictTree;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 字典
 *
 * @author jeecg
 */
@Tag(name = "系统字典维护")
@Slf4j
@RestController
@RequestMapping("/sys/dict")
@RequiredArgsConstructor
public class SysDictController {

    private final ISysDictService sysDictService;

    @GetMapping("/getPage")
    public R<IPage<SysDict>> queryPageList(
            SysDict entity,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        return sysDictService.getPage(entity, new Page<SysDict>(pageNo, pageSize));
    }

    /**
     * @param entity
     * @return
     * @功能：新增
     */
    @PostMapping("/add")
    public R<String> add(@RequestBody SysDict entity) {
        return sysDictService.add(entity);
    }

    /**
     * @param entity
     * @return
     * @功能：编辑
     */
    @PostMapping("/edit")
    public R<String> edit(@RequestBody SysDict entity) {
        return sysDictService.edit(entity);
    }

    /**
     * 删除-id
     *
     * @param id
     * @return
     */
    @Operation(summary = "删除-id")
    @DeleteMapping("/delete")
    public R<String> delete(@RequestParam(name = "id") String id) {
        return sysDictService.delete(id);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Operation(summary = "批量删除")
    @DeleteMapping("/deleteBatch")
    public R<String> deleteBatch(@RequestParam(name = "ids") String ids) {
        return sysDictService.deleteBatch(ids);
    }

    /**
     * 导出excel
     *
     * @param response
     */
    @Operation(summary = "导出excel")
    @GetMapping("/exportXls")
    public void exportXls(HttpServletResponse response) {
        List<SysDict> list = sysDictService.list();
        ExcelUtil.exportExcel(list, "工作系数表", SysDict.class, response);
    }

    /**
     * 导入excel
     *
     * @param file
     * @param updateSupport：是否删除标识
     * @return
     */
    @Operation(summary = "导入excel")
    @PostMapping("/importExcel")
    public R<?> importWork(MultipartFile file, boolean updateSupport) throws Exception {
        // 监听： new ImportListener(updateSupport);
        ExcelResult<SysDict> result = ExcelUtil.importExcel(file.getInputStream(), SysDict.class, null);
        return R.ok(true, result.getAnalysis());
    }

    /**
     * 获取树形字典数据
     *
     * @param entity
     */
    @SuppressWarnings("unchecked")
    @GetMapping("/treeList")
    public R<List<SysDictTree>> treeList(SysDict entity) {
        List<SysDict> list = sysDictService.list(
                new LambdaQueryWrapper<SysDict>()
                        .like(StrUtil.isNotEmpty(entity.getDictName()), SysDict::getDictName, entity.getDictName())
                        .orderByDesc(SysDict::getCreateTime)
        );
        List<SysDictTree> treeList = list.stream().map(n -> new SysDictTree(n)).collect(Collectors.toList());
        return R.ok(treeList);
    }

    /**
     * 刷新缓存
     */
    @GetMapping("/refreshCache")
    public R<?> refreshCache() {
        return sysDictService.refreshCache();
    }

    /**
     * 获取字典数据
     *
     * @param dictCode
     * @return
     */
    @GetMapping("/getDictText/{dictCode}/{key}")
    public R<String> getDictText(@PathVariable("dictCode") String dictCode, @PathVariable("key") String key) {
        String text = sysDictService.queryDictTextByKey(dictCode, key);
        return R.ok(text);
    }

    /**
     * 获取字典数据 【接口签名验证】
     *
     * @param dictCode 字典code
     * @param dictCode 表名,文本字段,code字段  | 举例：sys_user,realname,id
     * @return
     */
    @GetMapping("/getDictItems/{dictCode}")
    public R<List<DictVO>> getDictItems(@PathVariable("dictCode") String dictCode) {
        List<DictVO> ls = sysDictService.getDictItems(dictCode);
        if (ls == null) {
            return R.fail("字典Code格式不正确！");
        }
        return R.ok(ls);
    }
}
